<template>
  <div class="filter-section">
    <span class="filter-label">利率配置</span>
    <div class="tag-container rate-container">
      <div class="input-group">
        <label class="input-label">利率(%)</label>
        <el-input-number
          class="rate-input"
          v-model="ratePercent"
          :min="0"
          :max="100"
          :step="0.01"
          :precision="2"
          size="large"
          controls-position="right"
          placeholder="请输入利率(%)"
        />
      </div>
      <div class="operator-symbol">+</div>
      <div class="input-group">
        <label class="input-label">固定金额(元)</label>
        <el-input-number
          class="rate-input"
          v-model="fixedAmount"
          :min="0"
          :max="100000000"
          :step="1"
          :precision="0"
          size="large"
          controls-position="right"
          placeholder="请输入固定金额(元)"
        />
      </div>

      <el-button size="large" type="success" class="rate-submit-btn" @click="onRateSubmit">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue"
import { ElMessage } from "element-plus"
import { getRatesReadApi, updateRateApi } from "../../../../../api/calculator/index"

// 防抖函数
const debounce = <T extends (...args: any[]) => any>(func: T, delay: number): T => {
  let timeoutId: ReturnType<typeof setTimeout>
  return ((...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func(...args), delay)
  }) as T
}

// Props
interface Props {
  selectedRangeId?: number
  selectedDateRangeId?: number
}

const props = withDefaults(defineProps<Props>(), {
  selectedRangeId: undefined,
  selectedDateRangeId: undefined
})

// Emits
const emit = defineEmits<{
  rateChange: [ratePercent: number | undefined, fixedAmount: number | undefined]
  rateSubmit: [ratePercent: number | undefined, fixedAmount: number | undefined]
}>()

/**
 * 利率配置 - 分离为两个独立字段
 * ratePercent: 利率百分比值 (rate_percent)
 * fixedAmount: 固定金额值 (fixed_amount)
 */
const rateTouched = ref<boolean>(false)
const ratePercent = ref<number | undefined>(undefined) // 利率百分比
const fixedAmount = ref<number | undefined>(undefined) // 固定金额
const currentRateId = ref<number | undefined>(undefined) // 存储当前利率记录的ID

// 初始化利率配置
const initializeRateConfig = () => {
  ratePercent.value = undefined
  fixedAmount.value = undefined
  rateTouched.value = false
  currentRateId.value = undefined
}

// 监听选中的日期区间变化
watch(
  () => props.selectedDateRangeId,
  async (newDateRangeId) => {
    if (newDateRangeId) {
      await loadRateBySelection()
    } else {
      initializeRateConfig()
    }
  },
  { immediate: true }
)

// 根据当前选中的金额区间与日期区间，从后台读取利率
const loadRateBySelection = async () => {
  console.log("loadRateBySelection")
  const dateRangeId = props.selectedDateRangeId
  if (!dateRangeId || !Number.isFinite(dateRangeId)) return

  try {
    const res = await getRatesReadApi({ date_range_id: dateRangeId })
    console.log("读取利率结果:", res)
    if (res.code === 200 && res.data) {
      // 存储利率记录ID
      currentRateId.value = res.data.rate_id
      console.log("读取到的利率记录ID:", currentRateId.value)

      // 读取利率百分比
      const serverRatePercent = res.data.rate_percent != null ? Number(res.data.rate_percent) : undefined
      if (Number.isFinite(serverRatePercent)) {
        ratePercent.value = serverRatePercent
      }

      // 读取固定金额
      const serverFixedAmount = res.data.fixed_amount != null ? Number(res.data.fixed_amount) : undefined
      if (Number.isFinite(serverFixedAmount)) {
        fixedAmount.value = serverFixedAmount
      }

      console.log("读取到的利率百分比:", ratePercent.value)
      console.log("读取到的固定金额:", fixedAmount.value)
    } else {
      // 无记录：清空数据
      currentRateId.value = undefined
    }
  } catch (e) {
    console.error("读取利率失败:", e)
  }
}

// 使用防抖处理提交函数
const handleRateSubmit = async () => {
  const rangeId = props.selectedRangeId
  const dateRangeId = props.selectedDateRangeId

  if (!rangeId || !Number.isFinite(rangeId)) {
    ElMessage.error("请先选择金额区间")
    return
  }
  if (!dateRangeId || !Number.isFinite(dateRangeId)) {
    ElMessage.error("请先选择到期日期")
    return
  }

  // 检查是否至少有一个值被输入
  if (
    (ratePercent.value == null || isNaN(Number(ratePercent.value))) &&
    (fixedAmount.value == null || isNaN(Number(fixedAmount.value)))
  ) {
    ElMessage.error("请至少输入利率或固定金额中的一个")
    return
  }

  try {
    const updateData: any = {
      range_id: rangeId,
      date_range_id: dateRangeId
    }

    // 添加利率百分比
    if (ratePercent.value != null && !isNaN(Number(ratePercent.value))) {
      updateData.rate_percent = ratePercent.value
    }

    // 添加固定金额
    if (fixedAmount.value != null && !isNaN(Number(fixedAmount.value))) {
      updateData.fixed_amount = fixedAmount.value
    }

    // 如果有现有记录ID，添加到请求中
    if (currentRateId.value) {
      updateData.rate_id = currentRateId.value
    }

    const upd = await updateRateApi(updateData)
    if (upd.code === 200) {
      ElMessage.success("利率配置已更新")
    } else {
      ElMessage.error(upd.message || "更新利率配置失败")
      return
    }

    // 提交后标记触摸
    rateTouched.value = true
  } catch (e) {
    console.error("提交失败:", e)
    ElMessage.error("提交失败")
  }

  emit("rateSubmit", ratePercent.value, fixedAmount.value)
}

// 防抖处理的提交函数（300ms延迟）
const onRateSubmit = debounce(handleRateSubmit, 300)

// 暴露方法给父组件
defineExpose({
  initializeRateConfig,
  loadRateBySelection,
  getRatePercent: () => ratePercent.value,
  getFixedAmount: () => fixedAmount.value
})
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.filter-label {
  font-weight: 500;
  color: #333;
  margin-right: 15px;
  min-width: 70px;
  font-size: 14px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.rate-container {
  gap: 16px;
  display: flex;
  align-items: center;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.input-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 2px;
}

.operator-symbol {
  font-size: 18px;
  color: #909399;
  margin: 0 8px;
  margin-top: 12px;
}

.rate-submit-btn {
  padding: 6px 16px;
  font-weight: 500;
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.rate-input.el-input-number) {
  width: 160px;
}

:deep(.rate-input .el-input__wrapper) {
  padding: 0 10px;
}

@media (max-width: 768px) {
  .rate-container {
    flex-wrap: wrap;
    gap: 12px;
  }

  .operator-symbol {
    order: 2;
    margin: 8px auto;
  }

  .rate-submit-btn {
    order: 3;
    width: 100%;
  }
}
</style>
